package com.shuziren.question.service.impl;

import com.baomidou.mybatisplus.core.batch.MybatisBatch;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuziren.abnormal.CustomException;
import com.shuziren.question.entity.dto.InterviewQuestionSetDTO;
import com.shuziren.question.entity.*;
import com.shuziren.question.entity.dto.UpdateInterviewQuestionSet;
import com.shuziren.question.mapper.InterviewQuestionMapper;
import com.shuziren.question.mapper.InterviewQuestionSetMapper;
import com.shuziren.question.mapper.ProblemsetandtopicMapper;
import com.shuziren.question.service.InterviewQuestionSetService;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;
import java.util.Map;

@Service
@SuppressWarnings("all")
public class InterviewQuestionSetServiceImpl extends ServiceImpl<InterviewQuestionSetMapper, InterviewQuestionSet> implements InterviewQuestionSetService {
    @Autowired
    private  InterviewQuestionSetMapper interviewQuestionSetMapper;
    @Autowired
    private  InterviewQuestionMapper interviewQuestionMapper;

    @Autowired
    private ProblemsetandtopicMapper problemsetandtopicMapper;
    @Autowired
    private SqlSession sqlSession;
    @Autowired
    private SqlSessionFactory sqlSessionFactory;



    /*@Transactional(rollbackFor = Exception.class)
    @Override
    public String addQuestionSet(InterviewQuestionSetDTO questionSetDTO) {
        if (questionSetDTO != null) {
            // 将 DTO 转换为实体类
            InterviewQuestionSet interviewQuestionSet = new InterviewQuestionSet();
            interviewQuestionSet.setName(questionSetDTO.getName());
            interviewQuestionSet.setCreatedAt(new Date());
            interviewQuestionSet.setUpdatedAt(new Date());
            interviewQuestionSet.setStatus(questionSetDTO.getStatus());
            interviewQuestionSet.setPosition(questionSetDTO.getPosition());
            interviewQuestionSet.setDifficulty(questionSetDTO.getDifficulty());
            interviewQuestionSet.setScore(questionSetDTO.getScore());

            // 插入题目集信息
            int insert = interviewQuestionSetMapper.insert(interviewQuestionSet);
            if (insert > 0) {
                Integer questionSetId = interviewQuestionSet.getId();

                // 获取题目列表
                List<InterviewQuestionVo> questionList = questionSetDTO.getQuestions();
                if (questionList != null && !questionList.isEmpty()) {
                    for (InterviewQuestionVo questionVo : questionList) {
                        // 转换题目 VO 到实体类
                        InterviewQuestion interviewQuestion = questionVo.toInterviewQuestion();
                        int questionInsert = interviewQuestionMapper.insert(interviewQuestion);
                        if (questionInsert <= 0) {
                            throw new CustomException("添加题目失败");
                        }

                        // 获取新插入题目的 ID
                        Integer questionId = interviewQuestion.getId();

                        // 插入到中间表 problemset_topic
                        ProblemsetTopic problemsetTopic = new ProblemsetTopic();
                        problemsetTopic.setQuestionsetId(questionSetId);
                        problemsetTopic.setTopicId(questionId);
                        int relationInsert = problemsetandtopicMapper.insert(problemsetTopic);
                        if (relationInsert <= 0) {
                            throw new CustomException("关联题目失败");
                        }
                    }
                    return "添加成功";
                } else {
                    return "题目集创建成功，但未添加题目";
                }
            } else {
                throw new CustomException("添加题目集失败");
            }
        }
        return "添加失败";
    }*/

    /**
     * 查询题目集关联的题目
     * @param id
     * @return
     */
    @Override
    public List<ProblemsetTopic> selectProblemsetTopic(int id) {
        QueryWrapper<ProblemsetTopic> problemsetTopicQueryWrapper = new QueryWrapper<>();
        problemsetTopicQueryWrapper.eq("problemset_id",id);
        try  {
            List<ProblemsetTopic> problemsetTopics = problemsetandtopicMapper.selectList(problemsetTopicQueryWrapper);
            return problemsetTopics;
        } catch (Exception e) {
            throw new CustomException("查询题目失败");
        }
    }

    /**
     * 添加面试题目集
     * @param questionSetDTO 题目集信息
     * @return 返回信息
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public String addQuestionSet(InterviewQuestionSetDTO questionSetDTO){
        // 检查参数是否为空，如果为空则抛出异常
        if (questionSetDTO == null) {
            throw new CustomException("参数不能为空");
        }

        // 将 InterviewQuestionSetDTO 转换为 InterviewQuestionSet 对象
        InterviewQuestionSet interviewQuestionSet = questionSetDTO.toInterviewQuestionSet();

        // 插入题目集基本信息到数据库
        int insert = interviewQuestionSetMapper.insert(interviewQuestionSet);
        if (insert <= 0) {
            // 如果插入失败，抛出异常
            throw new CustomException("添加题目集失败");
        }

        // 获取前端传递的题目列表（包含题目的 ID）
        List<Integer> list = questionSetDTO.getQuestions();
        if (list == null || list.isEmpty()){
            return "添加成功";
        }
        // 遍历题目列表，将每个题目与题目集关联
        for (Integer integer : list) {
            // 根据题目 ID 查询题目详情
            InterviewQuestion interviewQuestion = interviewQuestionMapper.selectById(integer);

            // 如果题目不存在，抛出异常
            if (interviewQuestion == null) {
                throw new CustomException("添加题目集失败");
            }

            // 创建 ProblemsetTopic 对象，用于记录题目集与题目的关联关系
            ProblemsetTopic problemsetTopic = new ProblemsetTopic();
            problemsetTopic.setQuestionsetId(interviewQuestionSet.getId()); // 设置题目集 ID
            problemsetTopic.setTopicId(integer); // 设置题目 ID

            // 插入关联关系到中间表
            int insert1 = problemsetandtopicMapper.insert(problemsetTopic);

            // 如果插入失败，抛出异常
            if (insert1 <= 0) {
                throw new CustomException("添加题目集失败");
            }
        }
        // 更新题目集的相关数据（如题目数量和总分）
        int i = this.dataUpdateQuestionSet(interviewQuestionSet.getId());
        if (i <= 0) {
            // 如果更新失败，抛出异常
            throw new CustomException("题目集添加失败");
        }
        // 返回成功信息
        return "添加成功";
    }

    /**
     * 删除面试题目集
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int removeQuestionSet(int id) throws CustomException{

        // 检查题目集是否存在
        InterviewQuestionSet interviewQuestionSet = interviewQuestionSetMapper.selectById(id);
        if (interviewQuestionSet == null) {
            throw new CustomException("题目集不存在");
        }

        // 删除题目集与题目的关联记录
        QueryWrapper<ProblemsetTopic> problemsetTopicQueryWrapper = new QueryWrapper<>();
        problemsetTopicQueryWrapper.eq("problemset_id", id);
        int delete = problemsetandtopicMapper.delete(problemsetTopicQueryWrapper);
        if (delete < 0) {
            throw new CustomException("删除关联记录失败");
        }

        // 删除题目集
        int deleteQuestionSet = interviewQuestionSetMapper.deleteById(id);
        if (deleteQuestionSet <= 0) {
            throw new CustomException("删除题目集失败");
        }
        return deleteQuestionSet;
    }

    @Override
    public boolean updateQuestionSet(InterviewQuestionSet questionSet) {
        List<Integer> list = questionSet.getQuestions();
         QueryWrapper<ProblemsetTopic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("problemset_id", questionSet.getId());
        int i = problemsetandtopicMapper.delete(queryWrapper);
        int update = interviewQuestionSetMapper.updateById(questionSet);
        if (update <= 0) {
            throw new CustomException("更新失败");
        }

        for (Integer integer : list) {
            try{
                int insert = problemsetandtopicMapper.insert(new ProblemsetTopic(questionSet.getId(), integer));
                if (insert <= 0){
                    throw new CustomException("修改失败");
                }
            }catch (Exception e){
                throw new CustomException("修改失败");
            }

        }

        int i1 = dataUpdateQuestionSet(questionSet.getId());
        if (i1 <= 0) {
            throw new CustomException("更新失败");
        }

        return true;
    }


    /**
     * 查询面试题目集
     * @param querySet
     * @return dtoPage
     */
    @Override
    public IPage<InterviewQuestionSet> selectQuestionSet(InterviewQuestionSetDTO querySet) {
        IPage<InterviewQuestionSet> questionSetPage = new Page<>(querySet.getPageNum(), querySet.getPageSize());
        QueryWrapper<InterviewQuestionSet> queryWrapper = new QueryWrapper<>();


        // 状态条件查询
        if (querySet.getStatus() != null) {
            queryWrapper.eq("status", querySet.getStatus());
        }

        // 职位条件查询
        if (querySet.getPosition() != null) {
            queryWrapper.eq("position", querySet.getPosition());
        }

        // 分页查询
        IPage<InterviewQuestionSet> pageResult = interviewQuestionSetMapper.selectPage(questionSetPage, queryWrapper);


        return pageResult;
    }

    /**
     * 更新题目集
     * @param id 题目集id
     * @return int
     */
    @Override
    public int dataUpdateQuestionSet(int id){
        // 创建 QueryWrapper 查询条件构造器，用于查询题目集的题目数量
        QueryWrapper<ProblemsetTopic> wrapper = new QueryWrapper<>();

        // 选择 problemset_id 和 topic_id 的统计信息，并按题目集 ID 进行过滤
        wrapper.select("problemset_id, count(topic_id) AS topic_id").eq("problemset_id", id);

        // 调用 Mapper 方法查询统计数据，返回 Map 列表
        List<Map<String, Object>> maps = problemsetandtopicMapper.selectMaps(wrapper);

        // 如果查询结果为空，抛出异常
        if (maps == null) {
            throw new CustomException("题目集更新数据错误");
        }

        // 获取第一个 Map 对象（假设只有一条记录）
        Map<String, Object> map = maps.get(0);

        // 获取题目数量
        Object topicId = map.get("topic_id");
        int i = Integer.parseInt(topicId.toString()); // 将题目数量转换为整数

        // 再次创建 QueryWrapper 查询条件构造器，用于查询题目集的所有题目
        QueryWrapper<ProblemsetTopic> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("problemset_id", id); // 按题目集 ID 过滤

        // 查询题目集的所有题目列表
        List<ProblemsetTopic> list = problemsetandtopicMapper.selectList(wrapper1);

        // 如果查询结果为空，抛出异常
        if (list == null) {
            throw new CustomException("题目集更新数据错误");
        }

        // 初始化题目集总分
        int Totalscore = 0;

        // 遍历题目列表，累加每个题目的分数
        for (ProblemsetTopic problemset_topic : list) {
            // 根据题目 ID 查询题目详情
            InterviewQuestion Question = interviewQuestionMapper.selectById(problemset_topic.getTopicId());

            // 如果题目不存在，抛出异常
            if (Question.getScore() != null) {
                // 累加题目分数
                Totalscore += Question.getScore();
            }
        }

        // 根据题目集 ID 查询题目集详情
        InterviewQuestionSet interviewQuestionSet = interviewQuestionSetMapper.selectById(id);

        // 如果题目集不存在，抛出异常
        if (interviewQuestionSet == null) {
            throw new CustomException("题目集更新数据错误");
        }

        // 创建新的 InterviewQuestionSet 对象，准备更新数据
        InterviewQuestionSet interviewQuestionSet1 = new InterviewQuestionSet();
        interviewQuestionSet1.setId(id); // 题目集 ID
        interviewQuestionSet1.setQuestionCount(i); // 题目数量
        interviewQuestionSet1.setScore(Totalscore); // 题目集总分
        interviewQuestionSet1.setName(interviewQuestionSet.getName()); // 原有名称
        interviewQuestionSet1.setPosition(interviewQuestionSet.getPosition()); // 原有位置
        interviewQuestionSet1.setStatus(interviewQuestionSet.getStatus()); // 原有状态
        interviewQuestionSet1.setDifficulty(interviewQuestionSet.getDifficulty()); // 原有难度
        interviewQuestionSet1.setCreatedAt(interviewQuestionSet.getCreatedAt()); // 原有创建时间

        // 执行更新操作
        QueryWrapper<InterviewQuestionSet> interviewQuestionSetQueryWrapper = new QueryWrapper<>();
        interviewQuestionSetQueryWrapper.eq("id", interviewQuestionSet1.getId());

        int update = interviewQuestionSetMapper.update(interviewQuestionSet1, interviewQuestionSetQueryWrapper);

        // 返回更新结果
        return update;
    }

}




